import logging
import random
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
from view_geek_info import random_sleep_time
import pyautogui
from time import sleep
# 切换到推荐牛人页面
def get_boss_bull_people(driver):
    try:
        # 获取当前页面 URL
        current_url = driver.current_url

        # 推荐牛人页面的 URL
        recommend_page_url = 'https://www.zhipin.com/web/chat/recommend'

        # 如果当前页面已经是推荐牛人页面，则跳过点击
        if recommend_page_url in current_url:
            logging.info("已经在推荐牛人页面，不需要再次点击")
            random_sleep_time()
        else:
            # 切换到推荐牛人页面
            recommend = WebDriverWait(driver, 10).until(
                EC.element_to_be_clickable((By.XPATH, '//*[@id="wrap"]/div[1]/div[1]/dl[2]/dt/a'))
            )
            # 创建 ActionChains 对象
            actions = ActionChains(driver)
            # 将鼠标移动到目标元素并点击
            actions.move_to_element(recommend).click().perform()
            # recommend.click()
            logging.info("进入推荐牛人页面")
            random_sleep_time()

        # 等待 iframe 加载并切换到该 iframe
        WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.NAME, 'recommendFrame')))

        # 在 iframe 内定位并点击目标元素
        # 如果页面元素显示取消筛选，则不执行筛选逻辑
        try:
            cancel_filter = '//*[@id="headerWrap"]/div/div/div[5]/div/div/div'
            cancel_filter_element = driver.find_element(By.XPATH, cancel_filter)
            weixin_number_texts = cancel_filter_element.text
            if weixin_number_texts == '取消筛选':
                logging.info("已经筛选-跳过筛选")

            else:
                # 点击筛选按钮
                filter = WebDriverWait(driver, 10).until(
                    EC.element_to_be_clickable((By.XPATH, '//*[@id="headerWrap"]/div/div/div[5]/div/div/div'))
                )
                # 创建 ActionChains 对象
                actions = ActionChains(driver)
                # 将鼠标移动到目标元素并点击
                actions.move_to_element(filter).click().perform()
                logging.info("进入筛选页面")
                random_sleep_time()

                # 活跃度选择
                # 调用示例
                liveness = WebDriverWait(driver, 10).until(
                    EC.element_to_be_clickable((By.XPATH,
                                                '//*[@id="headerWrap"]/div/div/div[5]/div/div[2]/div[1]/div[1]/div[2]/div[3]/div/div[2]/div[2]/div[1]/div[1]'))
                )
                # 创建 ActionChains 对象
                actions = ActionChains(driver)
                # 将鼠标移动到目标元素并点击
                actions.move_to_element(liveness).click().perform()
                # liveness.click()
                logging.info("筛选活跃度为：刚刚活跃")
                random_sleep_time()

                # 筛选求职意向
                Job_Intention = WebDriverWait(driver, 10).until(
                    EC.element_to_be_clickable((By.XPATH,
                                                '//*[@id="headerWrap"]/div/div/div[5]/div/div[2]/div[1]/div[2]/div[1]/div/div[2]/div[2]/div[1]'))
                )
                # 创建 ActionChains 对象
                actions = ActionChains(driver)
                # 将鼠标移动到目标元素并点击
                actions.move_to_element(Job_Intention).click().perform()
                logging.info("筛选求职意向为：离职-随时到岗")
                random_sleep_time()

                # 确定
                complete = WebDriverWait(driver, 10).until(
                    EC.element_to_be_clickable(
                        (By.XPATH, '//*[@id="headerWrap"]/div/div/div[5]/div/div[2]/div[2]/div[2]'))
                )
                # 创建 ActionChains 对象
                actions = ActionChains(driver)
                # 将鼠标移动到目标元素并点击
                actions.move_to_element(complete).click().perform()
                # complete.click()
                logging.info("完成筛选")
                random_sleep_time()

        except Exception as e:
            logging.info(e)

        # 生成一个随机数，范围在 45 到 55 之间
        random_count = random.randint(41, 43)
        for i in range(1, random_count + 1):  # li 从 1 到 随机生成的次数
            try:
                # 年龄判断，如果年龄在 18-28，则执行
                # 定位年龄元素
                age_xpath = f'//*[@id="recommend-list"]/div/ul/li[{i}]/div/div[1]/div[2]/div[2]/div'
                age_element = driver.find_element(By.XPATH, age_xpath)
                age_text = age_element.text

                # 提取“岁”前面的数字部分
                age = None
                if '岁' in age_text:
                    age = age_text.split('岁')[0]  # 使用 split 提取“岁”前面的部分
                    try:
                        age = int(age)  # 将提取的字符串转换为整数
                    except ValueError:
                        logging.error(f"第{i}年龄文本无法转换为整数: %s", age_text)
                        age = None
                # 判断年龄是否在 18-28 之外
                if age < 18 or age > 28:
                    logging.info(f"第{i}条年龄不在 18-28 之间，不符合用人要求，跳过")
                    for _ in range(3):
                        pyautogui.press('down')
                        sleep(0.2)
                    random_sleep_time()
                    continue

                # 判断年龄是在 18-28 之间
                if age >= 18 and age <= 28:
                    logging.info(f"第{i}条年龄在 18-28 之间，符合用人要求")
                    random_sleep_time()

                    # 构造 XPath，列表页打招呼
                    xpath_div_2 = f'//*[@id="recommend-list"]/div/ul/li[{i}]/div/div[3]/div[2]/span/div/button'
                    xpath_div_3 = f'//*[@id="recommend-list"]/div/ul/li[{i}]/div/div[3]/div[3]/span/div/button'
                    if xpath_div_2 or xpath_div_3 is True:
                        logging.info(f"第{i}条即将执行打招呼")

                    else:
                        logging.info(f"li{i}条已经打过招呼，执行下一条")
                        for _ in range(3):
                            pyautogui.press('down')
                            sleep(0.2)
                        continue

                    # 构造 推荐牛人详情页的 XPath
                    xpath_div_4 = f'//*[@id="recommend-list"]/div/ul/li[{i}]/div/div[1]/div[3]'  # 推荐牛人详情页
                    xpath_div_5 = './/div[1]/div[1]/div/div/div[1]/div/div[2]/div/div/div[1]/div/div/div[2]/div/span/div/button'  # 推荐牛人详情页打招呼按钮

                    # 随机选择点击 列表页打招呼 （35%)或 详情页打招呼（65%）
                    if random.random() < 0.35:
                        # 尝试点击 div[2] 或 div[3]
                        try:
                            # 点击 div[2]
                            say_hello = WebDriverWait(driver, 10).until(
                                EC.element_to_be_clickable((By.XPATH, xpath_div_2))
                            )
                            # 创建 ActionChains 对象
                            actions = ActionChains(driver)
                            # 将鼠标移动到目标元素并点击
                            actions.move_to_element(say_hello).click().perform()
                            logging.info(f"完成第[{i}]条打招呼")
                            for _ in range(3):
                                pyautogui.press('down')
                                sleep(0.2)
                            random_sleep_time()
                        except Exception as e:
                            logging.error(f"无法给第[{i}]条打招呼: 已经打过招呼")
                            for _ in range(3):
                                pyautogui.press('down')
                                sleep(0.2)
                            random_sleep_time()

                        try:
                            # 点击 div[3]
                            say_hello = WebDriverWait(driver, 10).until(
                                EC.element_to_be_clickable((By.XPATH, xpath_div_3))
                            )
                            # 创建 ActionChains 对象
                            actions = ActionChains(driver)
                            # 将鼠标移动到目标元素并点击
                            actions.move_to_element(say_hello).click().perform()
                            for _ in range(3):
                                pyautogui.press('down')
                                sleep(0.2)
                            logging.info(f"完成第[{i}]条打招呼")
                            random_sleep_time()
                        except Exception as e:
                            logging.error(f"第[{i}]条打招呼: 第一次失败")
                            for _ in range(3):
                                pyautogui.press('down')
                                sleep(0.2)
                        else:
                            logging.info(f"第[{i}]条已经打过招呼，执行下一条")
                            for _ in range(3):
                                pyautogui.press('down')
                                sleep(0.2)
                            random_sleep_time()
                            continue

                    else:
                        # 尝试点击 推荐牛人详情页 div[4] 和 打招呼按钮 div[5]
                        try:
                            # 点击 推荐牛人详情页
                            detail_button = WebDriverWait(driver, 10).until(
                                EC.element_to_be_clickable((By.XPATH, xpath_div_4))
                            )
                            # 创建 ActionChains 对象
                            actions = ActionChains(driver)
                            # 将鼠标移动到目标元素并点击
                            actions.move_to_element(detail_button).click().perform()
                            logging.info(f"进入推荐牛人详情页第{i}条")
                            random_sleep_time()

                            # 点击详情页打招呼按钮
                            say_hello_in_detail = WebDriverWait(driver, 10).until(
                                EC.element_to_be_clickable((By.XPATH, xpath_div_5))
                            )
                            # 创建 ActionChains 对象
                            actions = ActionChains(driver)
                            # 将鼠标移动到目标元素并点击
                            actions.move_to_element(say_hello_in_detail).click().perform()
                            logging.info(f"在推荐牛人详情页给第{i}条打招呼")
                            random_sleep_time()

                            # 关闭当前窗口
                            close_button = WebDriverWait(driver, 3).until(
                                EC.presence_of_element_located((By.CLASS_NAME, 'boss-popup__close'))
                            )

                            # 点击关闭按钮
                            # 创建 ActionChains 对象
                            actions = ActionChains(driver)
                            # 将鼠标移动到目标元素并点击
                            actions.move_to_element(close_button).click().perform()
                            logging.info("已关闭弹框。")
                            logging.info(f"关闭推荐牛人详情页第{i}条")
                            random_sleep_time()
                            for _ in range(3):
                                pyautogui.press('down')
                                sleep(0.2)

                        except Exception as e:
                            for _ in range(3):
                                pyautogui.press('down')
                                sleep(0.2)
                            random_sleep_time()
                            logging.error(f"无法给第{i}条打招呼，已经打过招呼")

                            # 关闭当前窗口
                            # 等待弹框关闭按钮的出现
                            close_button = WebDriverWait(driver, 3).until(
                                EC.presence_of_element_located((By.CLASS_NAME, 'boss-popup__close'))
                            )

                            # 点击关闭按钮
                            # 创建 ActionChains 对象
                            actions = ActionChains(driver)
                            # 将鼠标移动到目标元素并点击
                            actions.move_to_element(close_button).click().perform()
                            logging.info("已关闭弹框。")
                            random_sleep_time()
                            for _ in range(3):
                                pyautogui.press('down')
                                sleep(0.2)

                            logging.info(f"关闭推荐牛人详情页 li[{i}]")
                        else:
                            logging.info(f"第[{i}]条已经打过招呼，执行下一条")
                            random_sleep_time()
                            continue  # 继续下一轮循环

            except Exception as e:
                logging.error(f"处理第[{i}]条时发生错误: {e}")
                for _ in range(3):
                    pyautogui.press('down')
                    sleep(0.2)
                random_sleep_time()
                continue  # 继续下一轮循环

    except Exception as e:
        print(f"操作失败: {e}")
